﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//using ShopSignSpace;
using System.IO;
using LitJson;
using NewEditorNS;
using System;
//using WorldCheckerSp;

namespace CombinePicNS
{
    //160919 需要修改读取文件的方式 原为读取本地图片
    /// <summary>商铺招牌打包工具</summary>
    public class CombinePicUtil
    {
        //Dictionary<string, bool> buildDoneDic = new Dictionary<string, bool>();
        public static void Combine(JsonData areaJD, string routeID, string totalSignFolderPath, Action onDone = null)
        {
            string atlasFolderPath = totalSignFolderPath + "/"+routeID+"/areaConfig/";
            Directory.CreateDirectory(atlasFolderPath);

            //1.加载所有地块txt, 并获取所有建筑
            Dictionary<string, JsonData> build_jsonDic = new Dictionary<string, JsonData>();
            Dictionary<string, JsonData> area_jsonDic = new Dictionary<string, JsonData>();
            Dictionary<string, List<string>> build_picListDic = new Dictionary<string, List<string>>();
            //TODO songyi 160922 需要重新下载地块配置, 并按区块ID保存在不同txt文件下, 然后沿用原有逻辑

            //string[] txtArr = Directory.GetFiles(folderPath, "*.txt", SearchOption.TopDirectoryOnly);
            //for (int txtIndex = 0, txtNum = txtArr.Length; txtIndex < txtNum; txtIndex++)
            //{
            //    string areaTxtPath = txtArr[txtIndex];
            //    string areaName = SongeUtil.GetFileName(areaTxtPath);
            //    if (areaName.Length == 9)
            //    {
            //        //Debug.Log(areaName);
            //        string compAreaPath = areaTxtPath.Substring(0, areaTxtPath.Length - 4) + "_comp.txt";
            //        if (File.Exists(compAreaPath))
            //        {
            //            areaTxtPath = compAreaPath;
            //        }

            //        string areaStr = File.ReadAllText(areaTxtPath);
            //        JsonData areaJD = JsonMapper.ToObject(areaStr);
            //        area_jsonDic.AddRep(areaName, areaJD);
            //        for (int buildIndex = 0, buildNum = areaJD["build"].Count; buildIndex < buildNum; buildIndex++)
            //        {
            //            JsonData buildJD = areaJD["build"][buildIndex];
            //            //去掉原先的shops属性
            //            if (buildJD.Keys.Contains("shops"))
            //                buildJD["shops"] = null;
            //            if (buildJD.Keys.Contains("atlas"))
            //                buildJD["atlas"] = null;
            //            string buildName = buildJD["n"].ToString();
            //            build_jsonDic.AddRep(buildName, buildJD);
            //        }
            //    }
            //}



            area_jsonDic.AddRep(routeID, areaJD);
            JsonData buildJDList = areaJD["nodeList"];
            for (int buildIndex = 0, buildNum = buildJDList.Count; buildIndex < buildNum; buildIndex++)
            {
                JsonData buildJD = buildJDList[buildIndex];
                //去掉原先的shops属性
                if (buildJD.Keys.Contains("shops"))
                    buildJD["shops"] = null;
                if (buildJD.Keys.Contains("atlas"))
                    buildJD["atlas"] = null;
                string buildName = buildJD["guid"].ToString();
                build_jsonDic.AddRep(buildName, buildJD);
            }


            //2.遍历signArr文件夹下所有sign.txt, 获取到所有MianPianVO
            List<MianPianVO> mianList = new List<MianPianVO>();
            //string[] signFolderArr = Directory.GetDirectories(totalSignFolderPath);
            //for (int folderIndex = 0, folderNum = signFolderArr.Length; folderIndex < folderNum; folderIndex++)
            //{
            //string signFolderPath = signFolderArr[folderIndex] + "/";
            string signFolderPath = totalSignFolderPath + "/" + routeID;
            string signFolderName = SongeUtil.GetFolderPath(signFolderPath, false);



            string signStr = File.ReadAllText(signFolderPath + "/config.txt");
            JsonData signJD = JsonMapper.ToObject(signStr);
            bool isSame = false;
            List<MianPianVO> shopSignList = signJD["data"].ToItemVOList<MianPianVO>();
            for (int mianIndex = 0, mianNum = signJD["data"].Count; mianIndex < mianNum; mianIndex++)
            {
                //3.将所有MianPianVO 插入到对应建筑下
                JsonData mianJD = signJD["data"][mianIndex];
                MianPianVO mp = new MianPianVO();
                mp.ReadJsonData(mianJD);

                //CHECK 160423 没有放在当前照片包所包含的建筑上的面片不计入, 避免该建筑不能在对应的照片包中找招牌贴图
                //Debug.Log("ZP" + mp.BuildingName.Substring(0, 9) + "====" + "ZP" + signFolderName + "--->" + (("ZP" + mp.BuildingName.Substring(0, 9)) == signFolderName).ToString());
                //Debug.Log(mp.BuildingName + "--" + signFolderName);
                //if ("ZP" + mp.BuildingName.Substring(0, 9) == signFolderName)
                //{
                if (build_jsonDic.ContainsKey(mp.BuildingName) && mp.ShopSignList.Count != 0)
                {
                    mp.folderName = signFolderName;
                    mianList.Add(mp);

                    //3.1将面片的JsonData插入到对应building
                    string buildName = mp.BuildingName;

                    JsonData buildJD = build_jsonDic[mp.BuildingName];

                    if (!buildJD.Keys.Contains("shops") || buildJD["shops"] == null)
                        buildJD["shops"] = new JsonData();
                    buildJD["shops"].Add(mp.ToJsonData());

                    //3.2将照片图片加入对应列表 buildName-picList
                    foreach (var shopSignVO in mp.ShopSignList)
                    {
                        string SignCode = System.IO.Path.GetFileNameWithoutExtension(shopSignVO.SignCode);
                        string picName = totalSignFolderPath + "/" + signFolderName + "/sign/" + SignCode;
                        if (File.Exists(picName + ".png"))
                        {
                            isSame = true;
                            build_picListDic.AddToList(buildName, picName + ".png");
                            //buildDoneDic.AddRep(buildName, false);
                        }
                        else if (File.Exists(picName + ".jpg"))
                        {
                            isSame = true;
                            build_picListDic.AddToList(buildName, picName + ".jpg");
                        }
                        else
                        {
                            Debug.Log("有问题的图片名称 : " + picName);
                        }
                    }
                }
                //}
                if (!isSame)
                {
                    Debug.LogError(" 走向图ＺＰ文件夹与sign.txt里面的建筑名前九位不匹配  " + signFolderName + "  路径 = " + signFolderPath + "sign.txt");
                }
            }
            //}


            int leftAtlasBuildNum = build_picListDic.Keys.Count;
            //Debug.Log();

            //4.导出所有的图集 并插入图集信息到建筑JsonData
            foreach (var buildName in build_picListDic.Keys)
            {
                List<string> picList = build_picListDic[buildName];

                if (picList.Count == 0)
                    Debug.Log("picList.Count == 0!");

                int picNum = picList.Count;
                Texture2D[] textureArr = new Texture2D[picNum];//每个建筑所对应的tex列表
                int leftCount = picNum;

                for (int picIndex = 0; picIndex < picNum; picIndex++)
                {
                    //Debug.Log("buildName: " + buildName);
                    //string picFolderName = "ZP" + buildName.Substring(0, 9);
                    string picUrl = picList[picIndex];
                    string picName = SongeUtil.GetFileName(picUrl);
                    string tarBuildName = buildName;

                    //按建筑为单位, 加载所有单张图片
                    //Debug.Log(picUrl);
                    GetLocalPic(picUrl, tex2d =>
                    {
                        leftCount--;
                        //Debug.Log(tarBuildName + "-" + leftCount + "/" + picNum + ", " + picName + "\r\n"
                        //    + build_picListDic[tarBuildName].ForeachToString("\r\n"));
                        int texIndex = picList.IndexOf(picUrl);

                        textureArr[texIndex] = tex2d;

                        //Debug.Log("leftCount: " + leftCount);
                        if (leftCount == 0)
                        {
                            JsonData atlasJD = new JsonData();

                            #region 5.3版 PackTextures方法会裁切不能容纳的图片
                            //Rect[] rectArr = TexturePack(folderPath, textureArr, tarBuildName);

                            //for (int rectIndex = 0, rectNum = rectArr.Length; rectIndex < rectNum; rectIndex++)
                            //{
                            //    Rect rect = rectArr[rectIndex];
                            //    JsonData rectJD = new JsonData();

                            //    List<string> xx = picList;
                            //    rectJD["tile"] = SongeUtil.GetFileName(picList[rectIndex], true);
                            //    rectJD["atlas"] = tarBuildName;
                            //    rectJD["rect"] = rect.x + "," + rect.y + "," +
                            //        rect.width + "," + rect.height;
                            //    atlasJD.Add(rectJD);
                            //}

                            #endregion

                            #region 新版打包(易春光)
                            MaxRects mr = MaxRects.Instance;
                            atlasJD = mr.Combine(atlasFolderPath, textureArr, tarBuildName, picList);
                            #endregion

                            //TODO songyi 160922 读取atlas图片 并将atlas
                            for (int iAtlas = 0, nAtlas = atlasJD.Count; iAtlas < nAtlas; iAtlas++)
                            {
                                JsonData atlasPic = atlasJD[iAtlas];
                                string atlasName = atlasPic.ReadString("atlas");
                                byte[] byteArr = File.ReadAllBytes(atlasFolderPath + atlasName);
                                string atlasCrc = Crc32.CountCrc(byteArr).ToString();
                                atlasPic["atlasName"] = atlasName;
                                atlasPic["atlasCrc"] = atlasCrc;
                            }




                            Dictionary<string, JsonData> xxx = build_jsonDic;
                            build_jsonDic[tarBuildName]["atlas"] = atlasJD;

                            leftAtlasBuildNum--;
                            //Debug.Log("leftAtlasBuildNum: " + leftAtlasBuildNum);
                            //Debug.Log(tarBuildName+"加载完成, 剩余建筑: " + leftAtlasBuildNum + "/" + build_picListDic.Keys.Count);
                            //buildDoneDic.AddRep(tarBuildName, true);
                            if (leftAtlasBuildNum == 0)
                            {
                                //5.保存所有的地块txt 到areaConfig文件夹
                                foreach (var areaName in area_jsonDic)
                                {
                                    Directory.CreateDirectory(atlasFolderPath);
                                    string areaItemPath = atlasFolderPath + "/" + areaName.Key;
                                    JsonData areaItemJD = areaName.Value;
                                    string saveAreaItem = JsonMapper.ToJson(areaItemJD);
                                    File.WriteAllText(areaItemPath + ".txt", saveAreaItem);
                                }
                                Debug.Log("打包图集完成!");
                                if (onDone != null)
                                    onDone();
                            }
                        }
                    });
                }
            }
        }

        static void GetLocalPic(string url, Action<Texture2D> callback)
        {
            LoadManager_WWW.instance.Load("file:///" + url, www =>
            {
                if (www.error == null && www.isDone)
                {
                    callback(www.texture);
                }
            }, (www, msg) => { Debug.Log("GetLocalPic - load fail! " + url); }, true, 0);
        }

        static Rect[] TexturePack(string folderPath, Texture2D[] textureArr, string atlasName)
        {
            string atlasFolder = folderPath + "/areaConfig/"; //NOTE 修改为atlasFolderPath
            Directory.CreateDirectory(atlasFolder);
            Texture2D altas = new Texture2D(1024, 1024);
            Rect[] rects = altas.PackTextures(textureArr, 2, 1024);
            byte[] buffer = altas.EncodeToPNG();
            File.WriteAllBytes(atlasFolder + atlasName + ".png", buffer);
            return rects;
        }
    }

    public class MianPianVO : IJsonData
    {
        public string BuildingName;
        public List<Vector3> pointList;
        public List<ShopSignVO> ShopSignList;

        public string folderName;

        public JsonData ToJsonData()
        {
            JsonData jd = new JsonData();

            jd["buildName"] = BuildingName;
            List<string> dataList = pointList.ConvertAll<string>((vec) => { return JsonUtils.vecToStr(vec); });
            jd["pointList"] = JsonUtils.ToJsonData(dataList);
            jd["shopSignList"] = ShopSignList.ToJsonDataList<ShopSignVO>();
            return jd;
        }

        public IJsonData ReadJsonData(JsonData jd)
        {
            if (jd.Keys.Contains("buildName"))
                BuildingName = jd["buildName"].ToString();
            if (jd.Keys.Contains("pointList"))
                pointList = jd["pointList"].ToVec3List();
            if (jd.Keys.Contains("shopSignList"))
                ShopSignList = jd["shopSignList"].ToItemVOList<ShopSignVO>();
            return this;
        }
    }
}
